package com.fangcun.common.util.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.fangcun.bean.admin.user.response.LoginResponse;
import com.fangcun.common.auth.UserAuthMethod;
import com.fangcun.common.auth.UserAuthMethod.LoginRedisKey;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.canstant.PublicConstant;
import com.fangcun.common.exception.ProException;
import com.fangcun.common.exception.ProValiDataException;
import com.fangcun.common.redis.RedisService;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.common.util.json.JSONTools;

/**
 * @作者： 陳曉鬆 @时间： 2018年3月8日 - 下午2:54:24 @description：->
 */
public class BaseAdminController {

	@Autowired
	private RedisService redisService;

	/** 获取AdminUserId **/
	public Long getAdminUserId() throws ProException {
		return UserAuthMethod.getLoginRedisKeyClass(PublicMethod.getRequest().getHeader(UserAuthMethod.LOGIN_TOKEN_NAME)).getUserId();
	}

	/** 获取后台ParamUserId **/
	public Long getAdminParamUserId() throws ProException {
		LoginRedisKey loginRedisKey = UserAuthMethod.getLoginRedisKeyClass(PublicMethod.getRequest().getHeader(UserAuthMethod.LOGIN_TOKEN_NAME));
		Long userId = loginRedisKey.getUserId();
		if (StringUtils.isEmpty(loginRedisKey.getAccount())) {
			throw new ProValiDataException(ErrCode.USER_LOGIN_TOKEN_FAIL.getReturnCode(), ErrCode.USER_LOGIN_TOKEN_FAIL.getReturnMsg() + "：未获取到帐号");
		}
		if (PublicConstant.BACK_SUPER_ACCOUNT.equals(loginRedisKey.getAccount())) {
			userId = null;// 超级管理员
		}
		return userId;
	}

	/** 获取RedisKey **/
	public String getRedisKey() throws ProException {
		return UserAuthMethod.getLoginRedisKeyClass(PublicMethod.getRequest().getHeader(UserAuthMethod.LOGIN_TOKEN_NAME)).getRedisKey();
	}

	/** 获取后台用户信息 **/
	public LoginResponse getAdminUser() throws ProException {
		Object obj = redisService.get(UserAuthMethod.LOGIN_REDIS_DB,
				UserAuthMethod.getLoginRedisKeyClass(PublicMethod.getRequest().getHeader(UserAuthMethod.LOGIN_TOKEN_NAME)).getRedisKey());
		if (obj == null) {
			throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
		}
		LoginResponse adminuser = JSONTools.jsonStr2obj(obj.toString(), LoginResponse.class);
		if (adminuser == null) {
			throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
		}
		return adminuser;
	}
	
	/** 获取茶楼id **/
	public Long getTeahouseId() throws ProException {
		if (getAdminParamUserId() == null) {
			return null;
		} else {
			return getAdminUser().getTeahouse().getId();
		}
	}
}
